package online.hxstart.code.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author huxing
 * @date 19-4-4 星期四 下午3:59
 * @describe
 */
public class TwoSum {
  public static int[] twoSum1(int[] nums, int target) {
    int len = nums.length;
    int dt;
    Set<Integer> set = Arrays.stream(nums).boxed().collect(Collectors.toSet());
    for (int i = 0; i < len; i++) {
      dt = target - nums[i];
      if (!set.add(dt)) {
        for (int j = 1 + 1; j < len; j++) {
          if (nums[j] == dt) {
            return new int[] {i, j};
          }
        }
      }
    }
    return null;
  }

  public static int[] twoSum2(int[] nums, int target) {
    int len = nums.length;
    Map<Integer, Integer> map = new HashMap<>(len);
    int dt;
    map.put(nums[0], 0);
    for (int i = 1; i < len; i++) {
      dt = target - nums[i];
      if (map.containsKey(dt)) {
        return new int[] {i, map.get(dt)};
      }
      map.put(nums[i], i);
    }
    return null;
  }

  public static void main(String[] args) {
    System.out.println(Arrays.toString(twoSum2(new int[] {3, 2, 4}, 6)));
  }
}
